package com.derbysoft.synxisadapter.commons.log;

import com.derbysoft.synxisadapter.commons.model.TransactionDetail;
import com.derbysoft.synxisadapter.commons.model.TransactionLog;
import com.derbysoft.synxisadapter.commons.repository.TransactionLogRepository;
import com.derbysoft.synxisadapter.commons.utils.XMLUtils;
import org.apache.commons.collections.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Created by: jason
 * Date: 2012-08-30
 */
public class TransactionLogTask implements Runnable {
    private TransactionLogRepository transactionLogRepository;
    private TransactionLog transactionLog;
    private Set<LogDetailPair> logDetailPairs;

    public TransactionLogTask(TransactionLogRepository transactionLogRepository,
                              TransactionLog transactionLog, Set<LogDetailPair> logDetailPairs) {
        this.transactionLogRepository = transactionLogRepository;
        this.transactionLog = transactionLog;
        this.logDetailPairs = logDetailPairs;
    }

    @Override
    public void run() {
        saveLog();
    }

    private void saveLog() {
        List<TransactionDetail> transactionDetails = new ArrayList<TransactionDetail>();
        if (CollectionUtils.isNotEmpty(logDetailPairs)) {
            for (LogDetailPair logDetailPair : logDetailPairs) {
                for (Object otaObject : logDetailPair.getOtaObjects()) {
                    TransactionDetail transactionDetail = new TransactionDetail();
                    transactionDetail.setDirection(logDetailPair.getDirection());
                    transactionDetail.setDetail(XMLUtils.toXML(otaObject));
                    transactionDetail.setTransactionLog(transactionLog);
                    transactionDetails.add(transactionDetail);
                }
            }
        }
        transactionLog.setTransactionDetails(transactionDetails);
        transactionLogRepository.create(transactionLog);
    }
}
